<template>
  <!-- 用户信息展示 -->
  <div class="user-info">
    <!-- 头像部分 -->
    <div class="avatar-section">
      <!-- 真实姓名 -->
      <div class="name">
        {{ friendData.realname }}
      </div>
      <q-avatar
        size="100px"
        class="shadow-5"
      >
        <img :src="friendData.avatar_url || '~/assets/images/logo.png'">
      </q-avatar>

      <!-- 个性签名 -->
      <div class="signature">
        "{{ friendData.signature || '这个人很懒，什么都没留下~' }}"
      </div>
    </div>

    <!-- 个人信息展示 -->
    <div class="details">
      <div class="name">
        昵称： {{ friendData.nickname || friendData.username }}
      </div>
      <div class="username">
        ID: {{ friendData.username }}
      </div>

      <div class="info-row">
        <div class="info-item">
          <q-icon name="email" /> {{ friendData.email }}
        </div>
        <div class="info-item">
          <q-icon name="phone" /> {{ friendData.phone || '未绑定' }}
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          性别: {{ genderLabel }}
        </div>
        <div class="info-item">
          注册时间: {{ formatDate(friendData.date_joined) }}
        </div>
      </div>

      <q-chip
        v-if="friendData.last_login"
        icon="schedule"
        color="secondary"
        text-color="white"
        class="last-login"
      >
        最后登录：{{ formatDate(friendData.last_login) }}
      </q-chip>

      <!-- 个人简介 -->
      <div class="intro">
        "{{ friendData.intro || '' }}"
      </div>
    </div>
    <!-- 按钮 -->
    <q-btn
      icon="home"
      label="常用"
      dense
      color="primary"
      glossy
      class="edit-btn"
      to="/medium"
    />
    <!-- <q-btn
      v-if="String(myId) === String(friendData.id)"
      icon="edit"
      label="编辑"
      dense
      color="primary"
      glossy
      class="edit-btn"
      @click="openProfileEdit"
    />
    <q-btn
      v-else
      icon="home"
      label="返回我的主页"
      dense
      color="primary"
      glossy
      class="edit-btn"
      @click="returnHome"
    /> -->
  </div>
  <!-- 编辑对话框 -->
  <q-dialog
    v-model="showProfileDialog"
    persistent
  >
    <q-card style="width: 90%; max-width: 600px;">
      <q-card-section class="dialog-header">
        <div class="text-h6">
          编辑个人信息
        </div>
        <q-btn
          v-close-popup
          icon="close"
          flat
          round
          dense
          class="close-btn"
        />
      </q-card-section>

      <q-card-section>
        <q-form
          class="form-container"
          @submit="updateProfile"
        >
          <!-- 头像上传区域 -->
          <div class="q-mb-md">
            <div
              class="upload-area relative-position"
              @click="triggerFileInput"
            >
              <q-img
                v-if="profileForm.avatar_url"
                :src="profileForm.avatar_url"
                style="width: 100%; height: 133px"
                class="rounded-borders"
              >
                <div class="absolute-full overlay flex flex-center">
                  <q-icon
                    name="edit"
                    size="24px"
                    color="white"
                  />
                </div>
              </q-img>
              <div
                v-else
                class="empty-area flex flex-center column"
              >
                <q-icon
                  name="add_photo_alternate"
                  size="48px"
                />
                <div class="q-mt-sm">
                  点击上传图片
                </div>
              </div>

              <input
                ref="fileInput"
                type="file"
                accept="image/*"
                hidden
                @change="handleFileSelect"
              >
            </div>

            <div
              v-if="uploadProgress > 0"
              class="q-mt-sm"
            >
              <q-linear-progress :value="uploadProgress" />
              <div class="text-caption text-center q-mt-xs">
                上传中... {{ Math.round(uploadProgress * 100) }}%
              </div>
            </div>
          </div>

          <!-- 昵称 -->
          <q-input
            v-model="profileForm.nickname"
            label="昵称"
            outlined
            dense
            class="q-mb-md"
          />

          <!-- 手机号 -->
          <q-input
            v-model="profileForm.phone"
            label="手机号"
            outlined
            dense
            class="q-mb-md"
          />

          <!-- 性别 -->
          <div class="bg-grey-2 q-pa-sm rounded-borders">
            性别:
            <q-option-group
              v-model="profileForm.gender"
              :options="genderOptions"
              label="性别"
              outlined
              dense
              class="q-mb-md"
            />
          </div>
          <!-- 个性签名 -->
          <q-input
            v-model="profileForm.signature"
            label="个性签名"
            type="textarea"
            :rules="[v => maxLength(v, 200)]"
            outlined
            dense
            class="q-mb-md"
          />
          <!-- 个人简介 -->
          <Input
            v-model="profileForm.intro"
            label="个人简介"
            type="textarea"
            class="q-pt-md"
          />
          <!-- 真实姓名 -->
          <q-input
            v-model="profileForm.realname"
            label="真实姓名"
            :rules="[v => maxLength(v, 20)]"
            outlined
            dense
            class="q-mb-md"
          />
          <!-- 邮箱 -->
          <q-input
            v-model="profileForm.email"
            label="邮箱"
            type="email"
            outlined
            dense
            class="q-mb-md"
          />

          <!-- 提交按钮 -->
          <div class="row justify-end">
            <q-btn
              v-close-popup
              label="取消"
              flat
              color="primary"
              class="q-mr-sm"
            />
            <q-btn
              label="保存"
              type="submit"
              color="primary"
              glossy
            />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script>
import { useQuasar } from 'quasar';
import member from 'src/api/member.js';
import { defineComponent, ref, computed } from 'vue';
import { useAuthStore } from 'src/stores/auth.js';
import { useRouter } from 'vue-router';
import useValidation from 'src/composables/validation.js';

export default defineComponent({
  name: 'UserProfile',
  setup() {
    const $q = useQuasar();
    const auth = useAuthStore();
    const friendData = ref(auth.getFriend());
    const myData = ref(auth.getUser());
    const myId = ref(auth.getUser().id);
    // 在组件挂载时调用 fetchData
    // onMounted(() => {
    //   auth.removeFriend();
    //   friendData.value = myData.value;
    // });
    const showProfileDialog = ref(false);
    const updatingProfile = ref(false);
    const genderOptions = [
      { label: 'null', value: 0 },
      { label: '男', value: 1 },
      { label: '女', value: 2 },
      { label: '保密', value: 3 },
    ];
    // 计算属性：根据用户的gender值返回对应的label
    const genderLabel = computed(() => {
      const optionGender = genderOptions.find((option) => option.value === myData.value.gender);
      return optionGender ? optionGender.label : '未知';
    });
    const profileForm = ref({
      avatar_url: null,
      avatar: null,
      realname: myData.value.realname,
      nickname: myData.value.nickname,
      email: myData.value.email,
      phone: myData.value.phone,
      gender: myData.value.gender,
      birthday: myData.value.birthday,
      signature: myData.value.signature,
      intro: myData.value.intro,
    });

    const openProfileEdit = () => {
      profileForm.value = {
        ...myData.value,
        avatar_url: myData.value.avatar_url,
        avatar: null,
      };
      showProfileDialog.value = true;
    };
    const router = useRouter();
    const returnHome = () => {
      friendData.value = myData.value;
      auth.saveFriend(myData.value);
      // 触发页面刷新
      router.go(0); // 相当于 window.location.reload()
    };

    const updateProfile = async () => {
      try {
        updatingProfile.value = true;

        // 创建 FormData 对象
        const data = new FormData();
        // 定义需要排除的字段
        const excludedFields = ['avatar_url', 'id', 'groups', 'user_permissions', 'username', 'avatar'];
        // 遍历 profileForm 并添加字段到 FormData，排除指定字段
        // 使用 Object.keys 和 Array.forEach 替代 for...of
        Object.keys(profileForm.value)
          .filter((key) => !excludedFields.includes(key)) // 排除指定字段 // 跳过空值
          .filter((key) => (profileForm.value[key] !== null))
          .filter((key) => (profileForm.value[key] !== undefined))
          .filter((key) => (profileForm.value[key] !== ''))
          .forEach((key) => {
            const value = profileForm.value[key];
            if (value instanceof File) {
              data.append(key, value); // 文件类型直接添加
            } else {
              data.append(key, String(value)); // 其他类型转换为字符串后添加
            }
          });

        if (profileForm.value.avatar instanceof File) {
          data.append('avatar', profileForm.value.avatar);
        }

        // 打印 FormData 内容（调试用）
        // Array.from(data.entries()).forEach(([key, value]) => {
        //   console.log(`${key}: ${value}`);
        // });

        const response = await member.updateMember(myData.value.id, data);

        // console.log(response.data.data);
        auth.saveUser(response.data.data);
        myData.value = response.data.data;
        friendData.value = response.data.data;
        auth.saveFriend(response.data.data);

        if (response.status === 201 || response.status === 200) {
          $q.notify({ type: 'positive', message: '个人信息更新成功' });
        } else {
          $q.notify({ type: 'negative', message: `个人信息更新 失败 ${response.status} ${response.data}` });
        }
        showProfileDialog.value = false;
      } catch (error) {
        $q.notify({ type: 'negative', message: '更新失败' });
      } finally {
        updatingProfile.value = false;
      }
    };

    const formatDate = (date) => {
      if (!date) return '';
      const options = { year: 'numeric', month: 'long', day: 'numeric' };
      return new Date(date).toLocaleDateString(undefined, options);
    };

    // 上传相关状态
    // 上传相关状态
    const fileInput = ref(null);
    const isUploading = ref(false);
    const uploadProgress = ref(0);

    const triggerFileInput = () => {
      fileInput.value.click();
    };
    const handleFileSelect = async (event) => {
      const file = event.target.files[0];
      if (!file) return;

      // 文件验证
      if (!file.type.startsWith('image/')) {
        $q.notify({ type: 'negative', message: '请选择图片文件' });
        return;
      }
      if (file.size > 20 * 1024 * 1024) {
        $q.notify({ type: 'negative', message: '图片大小不能超过20MB' });
        return;
      }

      profileForm.value.avatar = file;

      // console.log(file);
      // console.log(myForm.value.image);

      // 预览图片
      const reader = new FileReader();
      reader.onload = (e) => {
        profileForm.value.avatar_url = e.target.result;
      };
      reader.readAsDataURL(file);
    };
    const {
      required,
      email,
      phone,
      minLength,
      maxLength,
    } = useValidation();

    return {
      profileForm,
      genderOptions,
      genderLabel,
      updatingProfile,

      myData,
      myId,
      friendData,

      fileInput,
      isUploading,
      formatDate,
      showProfileDialog,
      openProfileEdit,
      updateProfile,
      triggerFileInput,
      handleFileSelect,
      uploadProgress,
      returnHome,

      required,
      email,
      phone,
      minLength,
      maxLength,
    };
  },
  // watch: {
  //   'profileForm.avatar': function (file) {
  //     if (file) {
  //       const reader = new FileReader();
  //       reader.onload = (e) => {
  //         this.profileForm.avatar = e.target.result;
  //       };
  //       reader.readAsDataURL(file);
  //     }
  //   },
  // },
});
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.avatar-section {
  margin-right: 20px;
}

.details {
  text-align: left;
}

.info-row {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.signature {
  margin-top: 10px;
  font-style: italic;
  color: #666;
  max-width: 200px;
  /* 最大宽度 */
  overflow-wrap: break-word;
  /* 长单词换行 */
  word-break: break-all;
  /* 强制换行 */
}

.intro {
  margin-top: 10px;
  font-style: italic;
  color: #666;
}

.edit-btn {
  margin-top: 20px;
}
</style>
